//
// Created by Max on 2024/5/14.
//

#include "SaveWav.h"
#include "Properties.h"
#include "hr_common.h"

SaveWav::SaveWav(int channels, int rate, pcm_format format) {
    mHeader.riff_id = ID_RIFF;
    mHeader.riff_sz = 0;
    mHeader.riff_fmt = ID_WAVE;
    mHeader.fmt_id = ID_FMT;
    mHeader.fmt_sz = 16;
    mHeader.audio_format = FORMAT_PCM;
    mHeader.num_channels = channels;
    mHeader.sample_rate = rate;

    mHeader.bits_per_sample = pcm_format_to_bits(format);
    mHeader.byte_rate = (mHeader.bits_per_sample / 8) * channels * rate;
    mHeader.block_align = channels * (mHeader.bits_per_sample / 8);
    mHeader.data_id = ID_DATA;

    LOGE("SaveWav constructed!");
}

SaveWav::~SaveWav() {
    LOGD("destructed");
}

int SaveWav::fSeekAfterWavHeader() {
    return SaveFile::fSeekFile(sizeof(struct wav_header), SEEK_SET);
}

int SaveWav::saveWav2File(int frames) {
    mHeader.data_sz = frames * mHeader.block_align;
    mHeader.riff_sz = mHeader.data_sz + sizeof(mHeader) - 8;
    SaveFile::fSeekFile(0, SEEK_SET);
    SaveFile::writeToFile(&mHeader, sizeof(struct wav_header), 1);
    return MI_FAILURE;
}

int SaveWav::fSeekFileFileBegin() {
    return SaveFile::fSeekFile(0, SEEK_SET);
}

